# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None


class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        flag = 0
        cur_l1, cur_l2 = l1, l2
        result = ListNode(0)
        cur_node = result
        last_node = None
        while cur_l1 is not None or cur_l2 is not None:
            a = 0 if cur_l1 is None else cur_l1.val
            b = 0 if cur_l2 is None else cur_l2.val
            cur_sum = a + b + flag
            if cur_sum >= 10:
                flag = 1
                cur_sum -= 10
            else:
                flag = 0
            cur_node.val = cur_sum
            new_node = ListNode(0)
            cur_node.next = new_node
            last_node = cur_node
            cur_node = new_node
            if cur_l1 is not None:
                cur_l1 = cur_l1.next
            if cur_l2 is not None:
                cur_l2 = cur_l2.next
        if flag:
            cur_node.val = 1
        else:
            last_node.next = None
        return result

# 6%